/*
 * main.c
 *
 *  Created on: Aug 1, 2013
 *      Author: lxzhu
 */

#include <stdio.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>

#define NAME_BUFFER_SIZE 100
#define N 4
void onDraw();
void onDrawObjects(GLenum mode);
void onMouse(int button, int state, int x, int y);
void onProcessHits(GLint hits, GLuint buffer[]);
char* legend;
int main(int argc, char** argv) {
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
	glutCreateWindow("PickingMode");
	glutDisplayFunc(onDraw);
	glutMouseFunc(onMouse);
	glutMainLoop();
	return 0;
}
void onDraw() {
	glClear(GL_COLOR_BUFFER_BIT);
	onDrawObjects(GL_RENDER);
	glutSwapBuffers();
}

void onDrawObjects(GLenum mode) {

	if (GL_SELECT == mode)
		glLoadName(1);
	glBegin(GL_TRIANGLES);
	glVertex2f(-0.75, -0.75);
	glVertex2f(-0.5, -0.75);
	glVertex2f(-0.6, 0);
	glVertex2f(-0.9, 0.1);
	glEnd();
	//if (GL_SELECT == mode)
	//	glPopName();

	if (GL_SELECT == mode)
		glLoadName(2);
	glBegin(GL_POLYGON);
	glVertex2f(0, 0);
	glVertex2f(0.5, 0.2);
	glVertex2f(0.5, 0.8);
	glVertex2f(0.25, 0.5);
	glEnd();
	//if (GL_SELECT == mode)
	//	glPopName();
}

void onMouse(int button, int state, int x, int y) {
	GLint viewport[4];
	GLuint nameBuffer[NAME_BUFFER_SIZE];
	GLint hits;
	if (GLUT_LEFT_BUTTON == button && GLUT_DOWN == state) {

		glSelectBuffer(NAME_BUFFER_SIZE, nameBuffer);

		glRenderMode(GL_SELECT);
		//glInitNames and glPushName must be invoked after glRenderMode
		glInitNames();
		glPushName(0);
		glGetIntegerv(GL_VIEWPORT, viewport);
		glMatrixMode(GL_PROJECTION);
		glPushMatrix();
		glLoadIdentity();
		gluPickMatrix(x, (viewport[3] - y), N, N, viewport);
		gluOrtho2D(-1.0, 1.0, -1.0, 1.0);

		onDrawObjects(GL_SELECT);

		glMatrixMode(GL_PROJECTION);
		glPopMatrix();
		hits = glRenderMode(GL_RENDER);
		onProcessHits(hits, nameBuffer);
		glutPostRedisplay();
	}
}

void onProcessHits(GLint hits, GLuint buffer[]) {
	printf("hits:%d\t ", hits);
	GLuint* ptr = buffer;
	GLuint nameNum = 0;
	GLint i = 0;
	GLint j = 0;
	for (; i < hits; i++) {
		nameNum = *ptr;
		printf("number of names:%d\t", nameNum);
		ptr++;
		printf("z1 is %f\t", (float) *ptr / 0x7fffffff);
		ptr++;
		printf("z2 is %f\t", (float) *ptr / 0x7fffffff);
		ptr++;
		printf("names:");
		for (j = 0; j < nameNum; j++) {
			printf("%d\t", *ptr);
			ptr++;
		}
		printf("\n");
	}
}

